import React, { useEffect, useState } from 'react';
import { Button, Drawer, Form, Space, message } from 'antd';
import FormRender from '@/components/FormRender';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { getEmployeeList, transferCustomer } from '@/api';

interface Props {
  callback: () => void;
}

export default function useCustomerChange({ callback }: Props) {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [employeeList, setEmployeeList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [customerId, setCustomerId] = useState<number>();
  const formList = [
    {
      title: '',
      Items: [
        {
          label: '员工',
          name: 'followUpUserId',
          type: 'select',
          items: employeeList?.map((i) => {
            return { name: i.realName, value: i.userId };
          }),
          rules: [{ required: true }],
        },
      ],
    },
  ];
  const onClose = () => {
    form.resetFields();
    setOpen(false);
  };

  useEffect(() => {
    if (!open) return;
    setLoading(true);
    getEmployeeList({ pageNum: 1, pageSize: 10000 }).then((res) => {
      if (res?.content?.length) {
        setEmployeeList(res?.content);
      }
      setLoading(false);
    });
  }, [open]);

  const onpenDrawer = (data) => {
    setOpen(true);
    setCustomerId(data?.customerId);
  };

  const submit = async () => {
    const values = await form.validateFields();
    if (!values) return;
    setLoading(true);
    const params = {
      customerId,
      followUpUserId: values?.followUpUserId,
    };
    transferCustomer(params)
      .then((data) => {
        setLoading(false);
        if (!data) return;
        message.success('转派成功');
        callback?.();
        onClose();
      })
      .catch((err) => {
        throw err;
      });
  };

  const customerChangeDrawer = (
    <Drawer
      title='客户转派'
      width={720}
      onClose={onClose}
      open={open}
      extra={
        <Space>
          <Button onClick={onClose}>关闭</Button>
          <Button onClick={submit} type='primary' loading={loading}>
            提交
          </Button>
        </Space>
      }
    >
      <FormRender defaultData={{}} form={form} formItem={formList || []} />
    </Drawer>
  );

  return [onpenDrawer, customerChangeDrawer];
}
